/**
 * Express.js中间件示例
 */

//导入Express模块
const express = require("express");

//创建Express应用
const app = express();

//定义路由模块
const router = express.Router();

//Express http服务端口
const port = 3001;

//内置中间件：静态资源中间件express.static
app.use(express.static("public"));
app.use("/public", express.static("public"));

//内置中间件：解析json数据
app.use(express.json());

//内置中间件：url解析
app.use(express.urlencoded({ extended: false }));

//应用层中间件  app.use()
//未定义路由路径的中间件，应用每次收到请求时执行该回调函数
app.use(function (req, res, next) { 
    console.log(`应用层中间件：Url-${req.url}，Time-${new Date().toLocaleString()}`);
    next();
});

//可在应用层中间件中定义路径，实际上指定路径上的任意类型的http请求
app.use("/mw/:id", function (req, res, next) { 
    console.log(`指定路径的应用层中间件，http请求方法${req.method}`);
    next();
});

//路由层中间件，支持路由和中间件
router.use(function (req, res, next) { 
    console.log(`路由层中间件：Url-${req.url}，Time-${new Date().toLocaleString()}`);
    next();
});

router.get("/router_mw/:id", function (req, res) { 
    console.log(`路由层中间件，路由参数${req.params.id}`);
    res.send("渲染");
});

//使用路由层中间件
app.use(router);

//错误处理中间件
app.get("/test-error", function () { 
    throw new Error("Oops!");
});

app.use(function (err, req, res, next) { 
    console.error(err.message);
    res.status(500).send("服务器500错误！")
});

app.use("*", function (req, res) { 
    console.log("404 Not found");
    res.json({
        status: 404,
        title: "页面不存在"
    });
});

//启动Express服务
app.listen(port, function () { 
    console.log(`MyApp访问地址：http://127.0.0.1:${port}`);
});